package com.tanhua.admin.service.impl;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tanhua.admin.exception.BusinessException;
import com.tanhua.admin.interceptor.AdminHolder;
import com.tanhua.admin.mapper.AdminMapper;
import com.tanhua.admin.service.AdminService;
import com.tanhua.commons.utils.Constants;
import com.tanhua.commons.utils.JwtUtils;
import com.tanhua.model.domain.Admin;
import com.tanhua.model.dto.AdminDto;
import com.tanhua.model.vo.AdminVo;
import netscape.security.UserTarget;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class AdminServiceImpl implements AdminService {

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    //返回图片验证码
    @Override
    public void sendCode(String uuid, HttpServletResponse response) throws IOException {
        //1.调用工具类生成图片验证码
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(299, 97);
        String code = lineCaptcha.getCode();
        //将验证码存入redis
        redisTemplate.opsForValue().set(Constants.CAP_CODE + uuid, code);
        //3.输出验证码
        lineCaptcha.write(response.getOutputStream());
    }

    //后台登录
    @Override
    public Map login(AdminDto adminDto) {
        //1.获取dto参数并进行校验
        String username = adminDto.getUsername();
        String password = adminDto.getPassword();
        String code = adminDto.getVerificationCode();
        String uuid = adminDto.getUuid();
        //校验参数
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            throw new BusinessException("用户名或密码为空");
        }

        //redis的Key
        String key = Constants.CAP_CODE + uuid;

        //从缓存中获取验证码
        String redisCode = redisTemplate.opsForValue().get(key);
        //2.校验验证码
        if (StringUtils.isEmpty(code) || !code.equals(redisCode)) {
            throw new BusinessException("验证码异常!");
        }
        //验证通过,删除redis验证码
        redisTemplate.delete(key);
        //3.根据用户名查询用户
        LambdaQueryWrapper<Admin> warpper = new LambdaQueryWrapper<>();
        warpper.eq(Admin::getUsername, username);
        Admin admin = adminMapper.selectOne(warpper);

        //接受到的密码加密
        password = SecureUtil.md5(password);

        //4校验用户名密码
        if (admin == null || !password.equals(admin.getPassword())) {
            throw new BusinessException("用户名或者密码错误!");
        }

        //5.验证通过,生成返会token
        HashMap<String, Object> map = new HashMap<>();
        map.put("username", username);
        map.put("id", admin.getId());
        String token = JwtUtils.getToken(map);

        Long userId = admin.getId();

        //将token存入redis,销毁时间和token时间一起销毁
        redisTemplate.opsForValue().set("TOKEN_CODE"+userId,token,JwtUtils.getTokenTime(), TimeUnit.SECONDS);

        //6.构造返回值
        Map res = new HashMap();
        res.put("token", token);
        return res;
    }

    //登录用户详情
    @Override
    public AdminVo loginUserInfo() {
        Long userId = AdminHolder.getUserId();
        Admin admin = adminMapper.selectById(userId);
        return AdminVo.init(admin);
    }

    //退出登录
    @Override
    public ResponseEntity logOut() {
        //获取用户id
        Long userId = AdminHolder.getUserId();
        //清除redis当中的token
        redisTemplate.delete("TOKEN_CODE"+userId);
        return ResponseEntity.ok(null);
    }
}
